<template>
	<view class="logistics-modal">
		<!-- 顶部标题栏 -->
		<view class="modal-header">
			<h2 class="modal-title">选择退货物流</h2>
		</view>
		<!-- 搜索框 -->
		<view class="search-box">
			<uv-search v-model="keyword" bgColor="#FFFFFF" :showAction='false' placeholder="搜索快递公司"
				placeholderColor="#B1B1B1" />
		</view>
		<!-- 快递列表 -->
		<scroll-view class="logistics-list" scroll-y :scroll-top="scrollTop" :scroll-into-view="activeAnchor"
			scroll-with-animation>
			<template v-for="(group, letter) in companyList" :key="letter">
				<view class="letter-title" :id="`letter-${letter}`">{{ letter }}</view>
				<view class="logistics-item" v-for="item in group" :key="item.id" @click="selectLogistics(item)">
					{{ item.title }}
				</view>
			</template>
		</scroll-view>

		<!-- 右侧字母索引 -->
		<view class="alphabet-index">
			<view v-for="letter in alphabet" :key="letter" class="index-letter"
				:class="{ active: currentLetter === letter }" @click="scrollToLetter(letter)">
				{{ letter }}
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		watch,
		onUnmounted,
		nextTick
	} from 'vue';
	import {
		getMailCompany
	} from '@/api/other.js'
	const emit = defineEmits(['select']);
	const companyList = ref({});
	const originalData = ref([]);
	const keyword = ref('');
	const scrollTop = ref(0);
	const activeAnchor = ref('');
	const currentLetter = ref('A');
	const scrollTimer = ref(null);

	// 动态字母索引
	const alphabet = computed(() => {
		const letters = Object.keys(companyList.value).sort();
		return letters.includes('#') ? [...letters.filter(l => l !== '#'), '#'] : letters;
	});

	// 滚动到指定字母（修正版）
	const scrollToLetter = async (letter) => {
		currentLetter.value = letter;
		activeAnchor.value = `letter-${letter}`;
	};

	// 按 title_en 分组
	const groupCompanyByTitleEn = (data) => {
		const result = {};
		// 初始化字母键（A-Z 和 #）
		for (let i = 65; i <= 90; i++) {
			result[String.fromCharCode(i)] = [];
		}
		result['#'] = [];

		data.forEach(courier => {
			const titleEn = courier.title_en;
			if (!titleEn || typeof titleEn !== 'string') {
				result['#'].push(courier);
				return;
			}

			// 取首字母并大写
			const firstChar = titleEn[0].toUpperCase();
			if (/^[A-Z]$/.test(firstChar)) {
				result[firstChar].push(courier);
			} else {
				result['#'].push(courier);
			}
		});

		// 移除空字母组（可选）
		Object.keys(result).forEach(key => {
			if (result[key].length === 0 && key !== '#') {
				delete result[key];
			}
		});
		return result;
	};

	watch(keyword, () => {
		if (keyword.value) {
			uni.$uv.debounce(() => {
				const filtered = {};
				// 遍历原始数据重新过滤分组
				originalData.value.forEach(item => {
					if (item.title.includes(keyword.value)) {
						const firstChar = item.title_en?.[0]?.toUpperCase() || '#';
						filtered[firstChar] = filtered[firstChar] || [];
						filtered[firstChar].push(item);
					}
				});

				// 移除空分组
				Object.keys(filtered).forEach(key => {
					if (filtered[key].length === 0) {
						delete filtered[key];
					}
				});
				companyList.value = filtered;
			})
		} else {
			companyList.value = groupCompanyByTitleEn(originalData.value);
			return;
		}
	})

	// 获取数据
	const getCompanyList = async () => {
		const res = await getMailCompany();
		if (res.code === 200) {
			originalData.value = res.result;
			companyList.value = groupCompanyByTitleEn(res.result);
			// 数据加载后初始化第一个字母
			nextTick(() => {
				currentLetter.value = Object.keys(companyList.value)[0] || 'A';
			});
		}
	};
	watch(alphabet, (newVal) => {
		if (newVal.length > 0 && !newVal.includes(currentLetter.value)) {
			currentLetter.value = newVal[0];
		}
	}, {
		immediate: true
	});
	// 选择快递公司
	const selectLogistics = (e) => {
		emit('select', e);
	};
	onMounted(() => {
		getCompanyList();
	});
	onUnmounted(() => {
		keyword.value = '';
	});
</script>

<style lang="scss" scoped>
	.logistics-modal {
		width: 100%;
		height: 80vh;
		/* 固定高度 */
		display: flex;
		flex-direction: column;
		position: relative;
		/* 关键 */
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		border-bottom: 1px solid #f0f0f0;
	}

	.modal-title {
		font-size: 18px;
		font-weight: 500;
		margin: 0;
		text-align: center;
		flex: 1;
	}
	
	.search-box {
		height: 40px;
	}

	.logistics-list {
		flex: 1;
		overflow-y: scroll !important;
		-webkit-overflow-scrolling: touch;
		position: relative;
	}

	.letter-title {
		padding: 5px 15px;
		font-size: 14px;
		color: #666;
		background-color: #f5f5f5;
		position: sticky;
		top: 0;
		z-index: 10;
		/* 确保在内容上方 */
	}

	.logistics-item {
		padding: 12px 15px;
		font-size: 15px;
		border-bottom: 1px solid #f0f0f0;
		cursor: pointer;
	}

	.logistics-item:active {
		background-color: #f5f5f5;
	}

	.alphabet-index {
		position: absolute;
		right: 10px;
		top: 50%;
		transform: translateY(-50%);
		z-index: 100;
	}

	.index-letter {
		padding: 2px 5px;
		cursor: pointer;
	}

	.index-letter.active {
		color: orange;
		font-weight: bold;
	}
</style>